<template>
  <div>
    <div class="userTop">
      <!-- 搜索框 -->
      <div class="userSearch">
        <!-- 查找名字 -->
        <form-input
          class="userSearchInput"
          placeholder="搜索成员"
          v-model="filterUser"
        >
        </form-input>
      </div>
      <div class="topLeft">
        <el-button type="primary" v-if="setShow" @click="addUser">
          <i class="el-icon-plus"></i> 添加成员</el-button
        >
        <div class="setUp" v-if="!setShow">
          <span class="setUser" @click="setUserButton(), (ifSingle = false)">
            <i class="el-icon-s-custom"></i>设置角色</span
          >
          <span class="removeUser" @click="open(), (ifSingle = false)">
            <i class="el-icon-remove"></i>移除</span
          >
        </div>
      </div>
    </div>
    <!-- 成员展示框 -->
    <div class="userContent">
      <el-table
        ref="multipleTable"
        :data="tables"
        tooltip-effect="dark"
        style="width: 100%"
        :row-style="{ height: '40px' }"
        @row-click="clickRow"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="100"> </el-table-column>
        <el-table-column
          prop="username"
          label="姓名"
          width="420"
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            <i
              class="squireName"
              :style="colorArray[parseInt(scope.row.userId % 6)]"
              ><span v-if="scope.row.username.length !== 2">{{
                scope.row.username.substr(1)
              }}</span>
              <span v-if="scope.row.username.length == 2">{{
                scope.row.username
              }}</span>
            </i>
            <span>{{ scope.row.username }}</span>
          </template>
        </el-table-column>
        <el-table-column label="" width="60">
          <template slot-scope="scope">
            <div class="ignoreIcon">
              <i class="el-icon-more" @click.stop="openEdit"></i>
              <div class="checkTop" v-show="editShow" @mouseleave="leave()">
                <div
                  @click.stop="
                    setRole(scope.$index, scope.row), (ifSingle = true)
                  "
                >
                  <i class="el-icon-setting"></i> 设置角色
                </div>
                <div
                  @click.stop="
                    deleteUser(scope.$index, scope.row),
                      open(),
                      (ifSingle = true)
                  "
                >
                  <i class="el-icon-delete"></i> 移除成员
                </div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="subject" label="方向" width="320">
        </el-table-column>
        <el-table-column prop="role" label="角色" align="center">
          <template slot-scope="scope">
            <div class="userRole">
              {{ scope.row.role }}
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 设置角色 -->
    <div class="setUserBgc" v-show="setFormShow">
      <f-form
        :model="setUserForm"
        ref="setUserForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <div class="setRoleTitle">设置角色</div>
        <el-divider></el-divider>
        <div class="setRoleContent">
          <div v-if="memberShow">
            设置成员<span>{{ currentUser }}</span
            >在当前项目中的角色
          </div>
          <div v-if="!memberShow">
            设置<span>{{ userArray.length }}</span
            >名成员在当前项目中的角色
          </div>
        </div>
        <form-item label="角色" prop="role" :rules="[{ required: true }]">
          <el-select v-model="setUserForm.role" placeholder="请选择角色">
            <el-option
              v-for="item in roleOptions"
              :key="item.id"
              :label="item.label"
              :value="item.label"
            >
            </el-option>
          </el-select>
        </form-item>
        <el-divider></el-divider>
        <span class="viewPermissions"
          ><i class="el-icon-question"></i>查看角色权限</span
        >
        <form-item class="setButton">
          <el-button @click="resetForm('setUserForm')">取消</el-button>
          <el-button type="primary" @click="submitForm('setUserForm')"
            >确定</el-button
          >
        </form-item>
      </f-form>
    </div>
    <!-- 增加成员 -->
    <div class="setUserBgc" v-show="addFormShow">
      <f-form
        :model="addUserForm"
        ref="addUserForm"
        label-width="100px"
        class="addUser-ruleForm"
      >
        <div class="setRoleTitle">选择成员</div>
        <el-divider></el-divider>
        <form-input
          class="searchUser"
          placeholder="搜索成员"
          v-model="filterText"
        >
        </form-input>
        <ul
          class="infinite-list"
          v-infinite-scroll="load"
          style="overflow: auto"
        >
          <el-checkbox-group
            v-model="checkedUsers"
            class="demo-checkUser"
          >
            <el-checkbox
              v-for="user in FilterUsers"
              :label="user.id"
              :key="user.id"
              :disabled="alreadySelect.indexOf(user.id) == -1 ? false:true"
              >{{ user.username }}</el-checkbox
            >
          </el-checkbox-group>
        </ul>
        <el-divider></el-divider>
        <form-item class="addButton">
          <el-button @click="cancleForm('addUserForm')">取消</el-button>
          <el-button type="primary" @click="determineForm('addUserForm')"
            >确定</el-button
          >
        </form-item>
      </f-form>
    </div>
  </div>
</template>

<script>
import { mapState } from "vuex";
import {SearchItemUserAPI,SearchStudyAPI,EditeItemRoleAPI,RemoveItemRoleAPI,AddItemRoleAPI} from '@/api/utils'
export default {
  // 注入依赖
  inject: ["reload"],
  async mounted() {
    this.removeUserItem = this.itemId;
    const res = await SearchItemUserAPI(this.itemId)
    if (res.data.flag) {
          this.tableData = res.data.data;
          this.tableData.forEach((el)=>{
            this.alreadySelect.push(el.userId)
          })
          this.alreadySelect = JSON.parse(JSON.stringify(this.alreadySelect))
          this.checkedUsers = this.alreadySelect
        } else {
          this.$message.error("查询失败！");
        }
      
      const res1 = await SearchStudyAPI()
       if (res1.data.flag) {
          this.allUsers = res1.data.data;
        } else {
          this.$message.error("查询失败！");
        }
  },
  data() {
    return {
      // 成员名字
      filterUser: "",
      filterText: "",
      // 成员设置是否展示
      setShow: true,
      editShow: false,
      setFormShow: false,
      addFormShow: false,
      currentUser: "",
      alreadySelect:[],
      memberShow: true,
      currentRemove: 0,
      deleteArray: [],
      ifSingle: true,
      activeName: "first",
      checkedUsers: [],
      setUserArray: [],
      currentId: 0,
      allUsers: [],
      // 选中用户的数组
      userArray: [],
      tableData: [],
      //   颜色数组
      colorArray: [
        "background-color:#84e17e",
        "background-color:#73d897",
        "background-color:#56abfb",
        "background-color:#ff9f73",
        "background-color:#5dcfff",
        "background-color:#868af6",
      ],
      // 角色设置
      setUserForm: {
        role: "普通成员",
      },
      // 成员增加
      addUserForm: {},
      // 角色内容
      roleOptions: [
        { id: 1, label: "产品经理", value: "po" },
        { id: 2, label: "项目经理", value: "sm" },
        { id: 3, label: "普通成员", value: "team" },
      ],
    };
  },
  methods: {
    // 展示列表第一列的选择框
    handleSelectionChange(val) {
      this.multipleSelection = val;
      this.setShow = false;
      this.userArray = val;
      // if (this.userArray.indexOf(row.id) == -1) {
      //   this.userArray.push(row.id);
      // } else {
      //   this.userArray = this.userArray.filter((item) => item != row.id);
      // }
    },
    // 点击一行该行复选框被选中
    clickRow(row) {
      this.$refs.multipleTable.toggleRowSelection(row);
    },
    // 点击省略号出现选择框
    openEdit() {
      this.editShow = !this.editShow;
    },
    // 鼠标移出
    leave() {
      this.editShow = false;
    },
    // 添加成员
    addUser() {
      this.addFormShow = true;
    },
    // 设置角色
    setRole(index, row) {
      this.memberShow = true;
      this.currentUser = row.username;
      this.setFormShow = true;
      this.currentId = row.userId;
    },
    // 设置角色表单
    async submitForm() {
      this.setUserArray = [];
      let roleId = this.itemId;
      let role = this.setUserForm.role;
      // 返回所选的选项所有信息
      // for (let i = 0; i < this.roleOptions.length; i++) {
      //      var obj = this.roleOptions.find(item => {
      //        return item.label === role;
      // })
      // }
      // var roleValue = obj.value
      let roleString = "";
      if (!this.ifSingle) {
        this.userArray.forEach((element) => {
          this.setUserArray.push(element.userId);
        });
      } else {
        this.setUserArray.push(this.currentId);
      }
      this.setUserArray.forEach((e) => {
        roleString += e + "=" + role + ",";
      });
      roleString = roleString.substring(0, roleString.length - 1);
      return EditeItemRoleAPI(roleId,roleString).then(res=>{
        if (res.data.flag) {
            this.reload()
            this.$message.success('修改成功!');
          }else{
            this.$message.error('修改失败!');
          }
      })
    },
    // 取消设置
    resetForm() {
      this.setFormShow = false;
      // document.querySelector(".demo-ruleForm").reset();
      this.setUserForm.role = "普通成员";
    },
    // 添加成员取消设置
    cancleForm() {
      this.addFormShow = false;
    },
    // 移除成员
    deleteUser(index, row) {
      this.currentRemove = row.userId;
    },
    // 删除判断
    open() {
      this.$confirm("此操作将该成员移除, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.removeUser();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
          this.reload();
        });
    },
    // 移除成员操作
    async removeUser() {
      // 项目 id
      this.deleteArray = [];
      if (!this.ifSingle) {
        this.userArray.forEach((element) => {
          this.deleteArray.push(element.userId);
        });
      } else {
        this.deleteArray.push(this.currentRemove);
      }
      return RemoveItemRoleAPI(this.removeUserItem,this.deleteArray).then(res=>{
        if (res.data.flag) {
            this.reload()
            this.$message.success('删除成功!');
          }else{
            this.$message.error('删除失败!');
          }
      })
    },
    // 点击右上角设置角色
    setUserButton() {
      this.memberShow = false;
      this.setFormShow = true;
    },
    // 滚动条
    load() {
      this.count += 2;
    },
    // 点击增加表单按钮
    async determineForm() {
      // let userId = this.checkedCount;
      let userId = this.checkedUsers;
      let index = 0
      this.alreadySelect.forEach((el)=>{
        index = userId.indexOf(el)
        if(index !== -1){
          userId.splice(index,1)
        }
      })
      return AddItemRoleAPI(this.removeUserItem,userId).then(res=>{
        if (res.data.flag) {
            this.reload()
            this.$message.success('添加成功!');
          }else{
            this.$message.error('添加失败!');
          }
      })
    },
  },
  computed: {
    //  输入检索内容
    tables() {
      const filterUser = this.filterUser;
      if (filterUser) {
        return this.tableData.filter((data) => {
          return Object.keys(data).some((key) => {
            if (key == "username") {
              return String(data[key]).indexOf(filterUser) > -1;
            }
          });
        });
      }
      return this.tableData;
    },
    ...mapState("ItemAddUser", ["itemId"]),
    FilterUsers() {
      const filterText = this.filterText;
      if (filterText) {
        return this.allUsers.filter((data) => {
          return Object.keys(data).some((key) => {
            if (key == "username") {
              return String(data[key]).indexOf(filterText) > -1;
            }
          });
        });
      }
      return this.allUsers;
    },
  },
  watch: {
    userArray(all) {
      if (all.length == 0) {
        this.setShow = true;
      }
    },
  },
};
</script>

<style scoped>
/* 搜索成员框 */
.userSearch {
  width: 223px;
  margin-bottom: 10px;
}
.userTop {
  display: flex;
  width: 100%;
  justify-content: space-between;
}
.topLeft {
  margin-right: 10px;
}
.el-icon-plus {
  margin-right: 5px;
  font-size: 15px;
}
.setUp i {
  margin-right: 5px;
}
.setUp span {
  color: #aaaaaa;
  cursor: pointer;
}
.setUser {
  margin-right: 15px;
  display: inline-block;
  width: 100px;
  border-right: 1px solid #ddd;
}
/* 经过角色变成小手 */
.userContent /deep/ .el-table .cell {
  cursor: pointer;
}
.setUserBgc /deep/ .el-checkbox {
  font-size: 30px;
  margin-right: 50px;
}
/* 用户名前面的圆圈 */
.squireName {
  display: inline-block;
  width: 30px;
  height: 30px;
  border-radius: 15px;
  background-color: pink;
  color: white;
  font-size: 10px;
  vertical-align: middle;
  margin-right: 5px;
  line-height: 30px;
  text-align: center;
}
.userContent /deep/ .el-table .cell {
  line-height: 41px;
}
.userContent /deep/ .el-table__body-wrapper {
  height: 450px;
}
.userContent /deep/ .el-table::before {
  background-color: transparent;
}
.ignoreIcon {
  display: none;
  text-align: center;
  width: 25px;
  height: 23px;
  border-radius: 3px;
  background-color: #e7f1f9;
  line-height: 23px;
}
/* 鼠标经过省略号显示 */
.userContent /deep/ .el-table__body tr:hover .ignoreIcon {
  display: inline-block;
}
/* 姓名后面的省略号 */
.el-icon-more {
  font-size: 8px;
  color: #348ee3;
  transform: rotate(90deg);
  cursor: pointer;
}
.checkTop {
  position: absolute;
  top: 45px;
  left: -136px;
  width: 170px;
  height: 70px;
  background-color: white;
  text-align: left;
  box-shadow: 0 0 12px 0 rgba(10, 10, 10, 0.3);
  z-index: 10;
}
.checkTop div {
  height: 35px;
  line-height: 35px;
  padding: 0 0 0 15px;
  cursor: pointer;
}
.checkTop div i {
  color: #ccc;
}
.checkTop div:hover {
  background-color: #f3f3f3;
}

/* 设置角色表单 */
.setUserBgc {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 98;
  background-color: rgba(0, 0, 0, 0.5);
}
.setUserBgc .demo-ruleForm,
.addUser-ruleForm {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  width: 588px;
  max-height: 512px;
  /* padding: 10px 67px; */
  background-color: white;
  border-radius: 10px;
  box-sizing: border-box;
  z-index: 99;
}
.addUser-ruleForm {
  width: 400px;
}
.setRoleTitle {
  width: 100%;
  padding: 15px 0 0 20px;
}
.setRoleContent {
  width: 100%;
  padding-left: 20px;
  margin-bottom: 20px;
}
.setRoleContent span {
  width: 100px;
  height: 40px;
  background-color: #e1eefb;
  text-align: center;
  color: #57a1e8;
  border-radius: 3px;
  padding: 3px 5px;
  margin: 0 5px;
}
.setButton {
  float: right;
  padding-right: 40px;
}
.addButton {
  margin-left: 20px;
}
.demo-ruleForm /deep/ .el-form-item__label {
  line-height: 56px;
}
.viewPermissions {
  display: inline-block;
  padding-left: 20px;
  color: #bdbdbd;
  line-height: 55px;
  cursor: pointer;
}
/* 增加成员 */
.searchUser {
  width: 250px;
  margin-left: 10px;
}
.demo-checkUser {
  padding-left: 20px;
  width: 240px;
}
.infinite-list {
  height: 200px;
}
.userContent /deep/.el-table .cell {
  color: #666;
}
.userContent /deep/.twoLineCls {
  color:black;
}
.userContent /deep/.el-table th.el-table__cell,
.userContent /deep/.el-table tr,
.userContent /deep/.el-table {
  background-color: rgba(255, 255, 255, 0.3);
}
</style>